# -*- coding: utf-8 -*-
# 基于回译生成同义句语料
import sys
import uuid
import requests
import hashlib
from requests.adapters import HTTPAdapter

# 增加重连次数
requests.adapters.DEFAULT_RETRIES = 5
# 设置连接活跃状态为False
s = requests.session()
s.keep_alive = False

import time

YOUDAO_URL = 'https://openapi.youdao.com/api'
APP_KEY = '3bfe238237d8e1b9'
APP_SECRET = 'EX3J3sWmQ8RwhXuHwWLo02dW66hfyAPC'


def encrypt(signStr):
    hash_algorithm = hashlib.sha256()
    hash_algorithm.update(signStr.encode('utf-8'))
    return hash_algorithm.hexdigest()


def truncate(q):
    if q is None:
        return None
    size = len(q)
    return q if size <= 20 else q[0:10] + str(size) + q[size - 10:size]


def do_request(data):
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    return requests.post(YOUDAO_URL, data=data, headers=headers)


def connect(sentence, direction):
    q = sentence
    data = {}
    # 英文到中文翻译
    if direction == 'en_zh':
        data['from'] = 'en'
        data['to'] = 'zh-CHS'
    # 中文到英文翻译
    else:
        data['from'] = 'zh-CHS'
        data['to'] = 'en'
    data['signType'] = 'v3'
    curtime = str(int(time.time()))
    data['curtime'] = curtime
    salt = str(uuid.uuid1())
    signStr = APP_KEY + truncate(q) + salt + curtime + APP_SECRET
    sign = encrypt(signStr)
    data['appKey'] = APP_KEY
    data['q'] = q
    data['salt'] = salt
    data['sign'] = sign

    response = do_request(data)
    contentType = response.headers['Content-Type']
    if contentType == "audio/mp3":
        millis = int(round(time.time() * 1000))
        filePath = "合成的音频存储路径" + str(millis) + ".mp3"
        fo = open(filePath, 'wb')
        fo.write(response.content)
        fo.close()
    else:
        return response.json()['translation']


if __name__ == '__main__':
    chinese_file = "/data/corpus_hj/paper_random_5000.txt"
    save_file = "/data/corpus_hj/back_translation_5000.txt"
    fout = open(save_file, 'a', encoding='utf-8')
    with open(chinese_file, "r") as fr:
        lines = fr.readlines()
    result_list = []
    i = 0
    for sentence in lines:
        sentence = sentence.strip()
        i += 1
        if i % 10 == 0:
            print("执行了 %d 条" % i)
        # 1、中文翻译成英文
        en_result = connect(sentence, 'zh_en')
        # 2、回译成中文
        back_result = connect(en_result[0], 'en_zh')
        time.sleep(2)
        fout.write(sentence + "\t" + en_result[0] + "\t" + back_result[0] + "\n")
    fout.close()
